package GameDb.Task;

import GameDb.DbHandler;
import GameDb.JDBC.JDBCTemplate;
import GameDb.Task.common.DbTask;
import Protobuf.DbProto;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import io.netty.util.concurrent.Future;

import java.sql.Connection;
import java.util.Map;
import java.util.concurrent.Callable;


/**
 * @author jedi
 */
public class DbRegister implements DbTask {
    private final ChannelHandlerContext ctx;
    private final DbProto.Msg msg;

    public DbRegister(ChannelHandlerContext ctx,DbProto.Msg msg){
        this.ctx = ctx;
        this.msg = msg;
    }

    @Override
    public void run(Connection conn) throws Exception {
        String username = msg.getPlayer().getUsername();
        String psd = msg.getPlayer().getPsd();
        String sql = "INSERT IGNORE INTO user(username,password) VALUES(?,?)";
        Object[] objects={username,psd};
        JDBCTemplate jdbcTemplate = new JDBCTemplate();
        long id = (long)jdbcTemplate.selectDbOperate(conn,sql,1,objects);
        dealDb(ctx,id);
    }


    public void dealDb( ChannelHandlerContext ctx,long id) {
        System.out.println("注册");
        System.out.println(id);
        String clientChannelId = msg.getChannelId();
        if(id == 0){
            DbProto.Msg resSucMsg = DbProto.Msg.newBuilder().setMsgType(DbProto.Msg.MsgType.resSuc).setChannelId(clientChannelId)
                    .setPlayer(DbProto.Player.newBuilder().setId(0).setUsername(msg.getPlayer().getUsername()).build()).build();
            ctx.writeAndFlush(resSucMsg);
        }else {
            String name = msg.getPlayer().getName();
            long tid = 10000L;
            long guid = 10000L;
            Object[] objects = {id,name,tid,guid};
            InsertPlayer insertPlayer = new InsertPlayer(ctx,msg,objects);
            DbHandler.dbQueue.loadTask(insertPlayer);
        }
    }


}
